package com.mybatisflex.admin;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.mybatisflex.admin.interceptor.LoginInterceptor;
import com.mybatisflex.admin.spring.error.GlobalErrorResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource
    LoginInterceptor interceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/api/message/collect")
                .excludePathPatterns("/api/account/test")
                .excludePathPatterns("/api/account/login")
                .excludePathPatterns("/avatars/**")
                .excludePathPatterns("/")
                .excludePathPatterns("/error");
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(httpMessageConverter -> {
            List<MediaType> supportedMediaTypes = httpMessageConverter.getSupportedMediaTypes();
            return supportedMediaTypes.contains(MediaType.APPLICATION_JSON);
        });
        //使用 fastjson 进行序列化
        converters.add(new FastJsonHttpMessageConverter());
    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new GlobalErrorResolver());
    }


}
